<template>
  <div class="border-box">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :default-config="toolbarConfig" />
    <Editor
      v-model="valueHtml"
      style="height: 350px; overflow-y: hidden"
      :default-config="editorConfig"
      @on-created="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IToolbarConfig, IEditorConfig } from '@wangeditor/editor'
import $api from '@/api/index'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { useProxy } from '@/utils/proxy'
type InsertFnType = (url: string, alt?: string, href?: string) => void
const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  qiniuInfo: {
    type: Object,
    required: true
  },
  imgSize: {
    type: Number,
    default: 1
  }
})
const emits = defineEmits(['update:value'])
const { proxy } = useProxy()
const editorRef = shallowRef()
const valueHtml = computed({
  get() {
    return props.value
  },
  set(value) {
    emits('update:value', value)
  }
})
const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'bold',
    'underline',
    'italic',
    'color',
    'bgColor',
    'bulletedList',
    'numberedList',
    'todo',
    'justifyLeft',
    'justifyRight',
    'justifyCenter',
    'indent',
    'delIndent',
    'uploadImage',
    'insertTable',
    'codeBlock',
    'divider',
    'undo',
    'redo'
  ]
}
const editorConfig = ref<Partial<IEditorConfig>>({
  MENU_CONF: {
    uploadImage: {
      server: props.qiniuInfo?.uploadUrl,
      fieldName: 'file',
      maxFileSize: props.imgSize * 1024 * 1024, // 1M
      maxNumberOfFiles: 5,
      meta: {
        token: props.qiniuInfo?.qiniuToken
      },
      // 将 meta 拼接到 url 参数中，默认 false
      metaWithUrl: false,
      // 自定义增加 http  header
      headers: {
        token: props.qiniuInfo?.qiniuToken
      },
      // 跨域是否传递 cookie ，默认为 false
      withCredentials: true,
      // 超时时间，默认为 10 秒
      timeout: 5 * 1000,
      async customUpload(file: File, insertFn: InsertFnType) {
        let size = file.size / 1024 / 1024
        if (size > props.imgSize) {
          return proxy.$message.msgError(`请上传大小不超过${props.imgSize}MB的文件`)
        }
        let formData = new FormData()
        formData.set('file', file)
        formData.set('token', props.qiniuInfo.qiniuToken)
        formData.set('key', String(file.lastModified))
        $api.post(props.qiniuInfo.uploadUrl, formData, { token: props.qiniuInfo.qiniuToken }).then((res) => {
          const imgUrl = `${props.qiniuInfo.cdnDomainName}/${res.key}`
          insertFn(imgUrl)
        })
      }
    }
  },
  placeholder: '请输入内容'
})
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor: any) => {
  editorRef.value = editor
}
</script>

<style lang="scss" scoped>
.border-box {
  border: 1px solid #ccc;
}
</style>
